#!/usr/bin/env python3
# pylint: disable=not-callable, no-member
# indent = space
# tab-size = 4

import os, sys, threading, signal, re, subprocess, logging, logging.handlers
import urllib.request
from time import time, sleep, strftime, localtime
from datetime import timedelta
try:
    print('检测依赖 psutil')
    import psutil
except:
    print('检测到缺少依赖 psutil 尝试安装...')
    os.system('python3 -m pip install psutil')
    import psutil


ps = psutil


def timeout_exec(command, timeout=5, output=True):
    """
    执行 shell 超时自动杀进程
    call shell-command and either return its output or kill it
    if it doesn't normally exit within timeout seconds and return None
    """
    import tempfile, datetime
    start = datetime.datetime.now()
    # 这次的重点关注是这里
    script = '''#!/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:${PATH}
echo "Shell script in process $$"
set -e

'''
    script_file = tempfile.NamedTemporaryFile('wt')
    script_file.write(script + command)
    script_file.flush()

    logging.info(script_file.name)
    process = subprocess.Popen(
        ['sh', script_file.name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, close_fds=True)
    stdout, stderr = process.communicate()
    while process.poll() is None:
        now = datetime.datetime.now()
        if (now - start).seconds > timeout:
            os.kill(process.pid, signal.SIGKILL)
            os.waitpid(-1, os.WNOHANG)
            return ""
    return stdout


def check_output(cmd):
    return subprocess.check_output(cmd, shell=True, universal_newlines=True)


def sh_exec(cmd):
    return os.popen(cmd).read()


def trim_br(s):
    return s.replace('\n', '').replace('\r', '')


def get_ddedock_pid():
    PID_DDE_DOCK=trim_br(check_output("/usr/bin/ps -C dde-dock|tail -n 1|awk '{print $1}'"))
    # print(PID_DDE_DOCK)
    while(PID_DDE_DOCK == "PID"):
        out = timeout_exec("nohup dde-dock >/dev/null 2>&1 &").decode()
        print('timeout_exec(dde-dock)' + out)
        sleep(1)
        PID_DDE_DOCK=trim_br(check_output("/usr/bin/ps -C dde-dock|tail -n 1|awk '{print $1}'"))
        print('PID: ' + PID_DDE_DOCK)
    return PID_DDE_DOCK


if __name__ == "__main__":
    DDE_ERR = 0;
    pid = ps.Process().pid
    p_fullpath = ps.sys.argv[0]
    p_name = ps.os.path.basename(p_fullpath)
    print('current script pid : %d' % pid)
    print('current script info: %s' % p_fullpath)
    # print(ps.Process())
    # print(ps.os.path.basename(p_fullpath))
    s, t = ps.subprocess.getstatusoutput('ps aux|grep -v grep|grep python3|grep %s|grep -v %d|awk \'{print $2}\'' % (p_name, pid))
    # print(s)
    # print(t)
    if s == 0 and t != '':
        ps.os.kill(int(t), 9)
        print('killed process: %s' % t)
    # sys.exit()
    while(True):
        PID_DDE_DOCK = get_ddedock_pid()
        KILLER_SLEEP = 10
        # print(PID_DDE_DOCK)
        SHELL = "/usr/bin/top -bn 1 -p " + PID_DDE_DOCK + "|head -n 8|tail -n 1 |awk '{print $9}'"; #
        PID_CPU_PY = 0
        try:
            PID_CPU=float(trim_br(sh_exec(SHELL)));
            # print(PID_CPU);
            CPU_COUNT=float(trim_br(check_output('/usr/bin/cat /proc/cpuinfo |grep "model\ name"|wc -l')))
            # print(CPU_COUNT);
            PID_CPU_PY = PID_CPU/CPU_COUNT
        except Exception as e:
            print(e)
        print('%s    dde-dock[%s]: %s%%' % (strftime("%Y-%m-%d %H:%M:%S", localtime()), PID_DDE_DOCK, PID_CPU_PY) )
        if(PID_CPU_PY>10):
            DDE_ERR+=1
            if(DDE_ERR > 2):
                sh_exec('notify-send "dde-dock restarting. CPU: %d"' % PID_CPU_PY)
                sh_exec('killall dde-dock')
                sleep(2)
                sh_exec('nohup dde-dock >/dev/null 2>&1 &')
                KILLER_SLEEP = 30
        else:
            DDE_ERR=0
        sleep(KILLER_SLEEP)
